package message;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;

import javax.jms.*;

/**
 *  消息组 实例
 * @author Guojt
 * @date 2024/11/12 8:18
 */
public class JMSSender {
    private static String USERNAME = ActiveMQConnection.DEFAULT_USER;
    private static String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    private static String BROKER = ActiveMQConnection.DEFAULT_BROKER_URL;

    private QueueConnection connectionnect = null;
    private QueueSession session = null;
    private QueueSender sender = null;

    public JMSSender(){
        try{
            // 创建连接工厂
            ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER);
            // 创建连接
            connectionnect = activeMQConnectionFactory.createQueueConnection();
            connectionnect.start();

            session = connectionnect.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

            Queue queue = session.createQueue("queue1");
            sender = session.createSender(queue);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void sendMessageGroup() throws JMSException {
        //将多条消息作为一个组发送
        sendSequenceMessage("START_SEQUENCE");
        sendMessage("message1");
        sendMessage("message2");
        sendMessage("message3");
        sendSequenceMessage("END_SEQUENCE");
        connectionnect.close();
    }

    // 在消息组内发送消息
    private void sendMessage(String text) throws JMSException{
        TextMessage textMessage = session.createTextMessage(text);
        textMessage.setStringProperty("JMSXGroupID", "group1");
        sender.send(textMessage);
    }

    // 发送一条包含序列标记的空有效负载消息
    private void sendSequenceMessage(String marker) throws JMSException{
        BytesMessage bytesMessage = session.createBytesMessage();
        bytesMessage.setStringProperty("SequenceMarker", marker);
        bytesMessage.setStringProperty("JMSXGroupID", "group1");
        sender.send(bytesMessage);
    }

    public static void main(String[] args) {
        try {
            new JMSSender().sendMessageGroup();
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }
}
